package com.example.duoduo_calc;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";
    private boolean mChecked;
    private int mType;
    private final int mCountDownTime = 5 * 60;

    private static long mBaseTimer;
    private static int mAnsIndex;
    private static int mRemainCount, mCorrectCount, mAccuracyCount, mTotalNum;
    private String[] mSymbols = new String[4];

    private Button[] mBts = new Button[4];
    private TextView mSymbol, mNum1, mNum2, mTotal, mRemain, mCorrect, mAccuracy, mTimeCount, mJudge;

    private Timer mTimer = new Timer("计时器");
    private Timer mJudgeHideTimer= new Timer("判定用计时器");
    private Object mJudgeTimerCountLock = new Object();

    private static int mJudgeTimerCount = 0;
    private static String []mBtsText = new String[4];
    private static String mSymbolText, mNum1Text, mNum2Text;

    public static boolean isOrientationChange = false;

    private final Handler mTimeHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mChecked) {
                if (msg.arg1 == 0) {
                    mTimer.cancel();
                    mTimeCount.setText(String.valueOf(mCountDownTime));
                    showReport();
                }
            }
            if (null != mTimeCount) {
                mTimeCount.setText((String) msg.obj);
            }
        }
    };

    private TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            int time;
            if (mChecked)
                time = (int) (mCountDownTime - (SystemClock.elapsedRealtime() - mBaseTimer) / 1000);
            else time = (int) ((SystemClock.elapsedRealtime() - mBaseTimer) / 1000);

            String hh = new DecimalFormat("00").format(time / 3600);
            String mm = new DecimalFormat("00").format(time % 3600 / 60);
            String ss = new DecimalFormat("00").format(time % 60);
            String timeFormat = hh + "∶" + mm + "∶" + ss;
            Message msg = new Message();
            msg.obj = timeFormat;
            msg.arg1 = time;
            mTimeHandler.sendMessage(msg);
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            Toast.makeText(getApplicationContext(), "横屏", Toast.LENGTH_SHORT).show();
            Log.v(TAG, "My Debug Log: onConfigurationChanged 横屏");
        } else {
//            Toast.makeText(getApplicationContext(), "竖屏", Toast.LENGTH_SHORT).show();
            Log.v(TAG, "My Debug Log: onConfigurationChanged 竖屏");
        }
        isOrientationChange = true;
        recreate();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = MainActivity.this.getIntent();
        mTotalNum = intent.getIntExtra("total", -1);
        mType = intent.getIntExtra("type", -1);
        mChecked = intent.getBooleanExtra("challenge", false);
        if (mChecked) mTotalNum = 0;

        mJudge = findViewById(R.id.textJudge);
//        mJudge.setVisibility(View.INVISIBLE);

        mSymbol = findViewById(R.id.symbolText);
        mNum1 = findViewById(R.id.aText);
        mNum2 = findViewById(R.id.bText);

        mTotal = findViewById(R.id.totalText);
        mRemain = findViewById(R.id.remainText);
        mCorrect = findViewById(R.id.correctText);
        mAccuracy = findViewById(R.id.accuracyText);
        mTimeCount = findViewById(R.id.timeCountText);

        mBts[0] = findViewById(R.id.button0);
        mBts[1] = findViewById(R.id.button1);
        mBts[2] = findViewById(R.id.button2);
        mBts[3] = findViewById(R.id.button3);

        for (int i = 0; i < 4; i++) {
            if (mBts[i] != null) {
                mBts[i].setOnClickListener(MyOnClickListener);
            }
        }

        mSymbols[0] = "＋";
        mSymbols[1] = "－";
        mSymbols[2] = "×";
        mSymbols[3] = "÷";

        if (!isOrientationChange) {
            Log.v(TAG, "My Debug Log: Initialize");

            // 初始化分数
            mRemainCount = mTotalNum;
            mCorrectCount = 0;
            mAccuracyCount = 0;

            // 出题目
            generateQuestion();

            // 计时器
            mBaseTimer = SystemClock.elapsedRealtime();
        }
        mTimer.scheduleAtFixedRate(mTimerTask, 0, 1000L);

        updateView();
        Log.v(TAG, "My Debug Log: onCreate");
    }

    @Override
    public void onBackPressed() {
        showExitDialog();
    }

    public static void initData() {

    }

    static private class MyData {
        int mCorrectCount;
        int mAccuracyCount;
        int mTotalNum;
        int mRemainCount;
        int mSymbolText;
        int mNum1Text;
        int mNum2Text;
        String []mBtsText = new String[4];
        long mBaseTimer;
    }

    private void updateView(){
        mCorrect.setText(String.valueOf(mCorrectCount));
        mAccuracy.setText(String.valueOf(mAccuracyCount));
        mTotal.setText(String.valueOf(mTotalNum));
        if (!mChecked) mRemain.setText(String.valueOf(mRemainCount));

        mSymbol.setText(mSymbolText);
        mNum1.setText(mNum1Text);
        mNum2.setText(mNum2Text);
        for (int i = 0; i < 4; i++) {
            mBts[i].setText(mBtsText[i]);
        }
    }

    private void generateQuestion() {
        int n1, n2, ans;
        int[] array;
        int max;

        if (mType <= 2) {
            switch (mType) {
                case 0://10以内加减法
                    max = 10;
                    break;
                case 1://20以内加减法
                    max = 20;
                    break;
                case 2://100以内加减法
                    max = 100;
                    break;
                default:
                    Log.e("错误日志", "Type error!");
                    MainActivity.this.finish();
                    return;
            }
            int sym = (int) (Math.round(Math.random()));// 0:- , 1:+
            if (sym == 1) {
                mSymbolText = mSymbols[0];
                ans = (int) (Math.floor(Math.random() * (max - 1))) + 2;
                n1 = (int) (Math.floor(Math.random() * (ans - 1))) + 1;
                n2 = ans - n1;
            } else {
                mSymbolText = mSymbols[1];
                n1 = (int) (Math.floor(Math.random() * (max - 1))) + 2;
                n2 = (int) (Math.floor(Math.random() * (n1 - 1))) + 1;
                ans = n1 - n2;
            }
        } else { // 9 9 乘法
            mSymbolText = mSymbols[2];
            max = 81;
            n2 = (int) (Math.floor(Math.random() * (9 - 1))) + 2;
            n1 = (int) (Math.floor(Math.random() * (n2 - 1))) + 2;
            ans = n1 * n2;
        }

        mNum1Text = String.valueOf(n1);
        mNum2Text = String.valueOf(n2);

        array = generateAnswer(ans, 4, max);
        mAnsIndex = (int) (Math.floor(Math.random() * 4));
        int j = 1;
        for (int i = 0; i < 4; i++) {
            if (i == mAnsIndex) {
//                mBts[i].setText(String.valueOf(ans));
                mBtsText[i] = String.valueOf(ans);
            } else {
//                mBts[i].setText(String.valueOf(array[j++]));
                mBtsText[i] = String.valueOf(array[j++]);
            }
        }

        updateView();
    }

    void showResult(boolean b) {
        if (b) {
//            mJudge.setText(Html.fromHtml(right));
            mJudge.setText("对");
            mJudge.setTextColor(Color.GREEN);
        } else {
//            mJudge.setText(Html.fromHtml(wrong));
            mJudge.setText("错");
            mJudge.setTextColor(Color.RED);
        }

        synchronized (mJudgeTimerCountLock)
        {
            mJudgeTimerCount++;
        }
        mJudge.setVisibility(View.VISIBLE);
        mJudgeHideTimer.schedule(new TimerTask() {
            public void run() {
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
            }
        }, 500);
    }

    private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mJudgeTimerCount--;
                    if (mJudgeTimerCount == 0) {
                        mJudge.setVisibility(View.INVISIBLE);
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    View.OnClickListener MyOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int i;
            for (i = 0; i < 4; i++) {
                if (v.getId() == mBts[i].getId()) break;
            }
            showResult(i == mAnsIndex);

            if (i == mAnsIndex) mCorrectCount++;

            if (!mChecked) mRemainCount--;
            else mTotalNum++;

            mAccuracyCount = 100 - (mTotalNum - mCorrectCount - mRemainCount) * 100 / (mTotalNum - mRemainCount);

            updateView();

            if (!mChecked & mRemainCount <= 0) {
                mTimer.cancel();
                showReport();
            } else {
                generateQuestion();
            }
        }
    };

    int[] generateAnswer(int ans, int num, int range) {
        int[] ret = new int[num];
        int[] array = new int[range + 1];
        for (int i = 0; i < range + 1; i++) {
            array[i] = i;
        }
        array[0] = ans;
        array[ans] = 0;
        for (int i = 1; i < num; i++) {
            int r = (int) (Math.ceil(Math.random() * (range - i))) + i;
            int temp = array[i];
            array[i] = array[r];
            array[r] = temp;
        }
        System.arraycopy(array, 0, ret, 0, 4);
//        for (int i = 0; i < num; i++) ret[i] = array[i];
        return ret;
    }

    void showReport() {
        float aver = (SystemClock.elapsedRealtime() - mBaseTimer);
        aver = aver / mTotalNum / 1000;

        for (int i = 0; i < 4; i++) mBts[i].setEnabled(false);

        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
        dialog.setTitle("成绩清单");
        String msg = new String();
        msg += "数量： " + mTotal.getText() + "\n";
        msg += "分数： " + mAccuracy.getText() + "\n";
        msg += "用时： " + mTimeCount.getText() + "\n";
        msg += "平均： " + (aver) + "秒";
        dialog.setMessage(msg);
        dialog.setIcon(android.R.drawable.ic_dialog_alert);
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MainActivity.this.finish();
            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }

    private void showExitDialog(){
        final AlertDialog.Builder dialog =
                new AlertDialog.Builder(this);
//        dialog.setIcon(R.drawable.icon_dialog);
        dialog.setTitle("警告");
        dialog.setMessage("确定退出吗?");
        dialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                        finish();
                    }
                });
        dialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        dialog.show();
    }
}
